package com.miyu.system.config.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.miyu.plugins.exception.CosException;
import com.miyu.plugins.result.ResultSend;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全球异常处理
 * @author MIYU
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {
    /**
     * 全局异常拦截（拦截项目中的NotLoginException异常）
     * token异常时错误问题
     * @param nle
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    public Object handlerNotLoginException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response)
    {
        /* 打印堆栈，以供调试*/
        nle.printStackTrace();
        /* 判断场景值，定制化异常信息*/
        String message = "";
        if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "NOT_TOKEN";
        }
        else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "INVALID_TOKEN";
        }
        else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "TOKEN_TIMEOUT";
        }
        else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "BE_REPLACED";
        }
        else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "KICK_OUT";
        }
        else {
            message = "NOT_TOKEN";
        }
        return ResultSend.error();
    }

    /**
     * 处理程序系统异常
     * @param request 请求
     * @param e       e
     * @return {@link Object}
     */
    @ExceptionHandler(value = CosException.class)
    @ResponseBody
    public Object handlerCosException(HttpServletRequest request, Exception e){
        String code = ((CosException) e).getCode();
        String msg = ((CosException) e).getMsg();
        if(!StringUtils.isEmpty(code)){
            return ResultSend.exception(code,msg);
        }
        return ResultSend.exception(msg);
    }

}
